/*
 * @Author: 李一番
 * @Date: 2021-05-22 16:12:34
 * @Last Modified by: 李一番
 * @Last Modified time: 2021-05-23 10:29:02
 */

/**
 * @description 加密存储
 */

import { encrypt, decrypt } from 'crypto-js/aes'
import UTF8, { parse } from 'crypto-js/enc-utf8'
import ECB from 'crypto-js/mode-ecb'
import pkcs7 from 'crypto-js/pad-pkcs7'

export interface EncryptionParams {
  key: string
  iv: string
}

export class AesEncryption {
  private key // 加密使用的key
  private iv
  constructor(opt: EncryptionParams) {
    const { key, iv } = opt
    this.key = parse(key)
    this.iv = parse(iv)
  }
  get getOption() {
    return {
      mode: ECB, // 加密方式
      padding: pkcs7, // 填充方式
      iv: this.iv // 偏移量
    }
  }

  /**
   * @description AES加密
   * @param str 加密前数据
   * @returns 加密过后数据
   */
  encryptByAES(str: string) {
    const encrypted = encrypt(str, this.key, this.getOption)
    return encrypted.toString()
  }

  /**
   * @description AES解密
   * @param str 加密后数据
   * @returns 加密前数据
   */
  decryptByAES(str: string) {
    const encrypted = decrypt(str, this.key, this.getOption)
    return encrypted.toString(UTF8)
  }
}
